import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

// 设置路由白名单
const whiteList = ['/login', '/404']
// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  // 更改标题
  document.title = getPageTitle(to.meta.title)
  const { token } = store.state.user
  // 进度条开启
  NProgress.start()

  // 判断是否有 token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 获取用户信息(2个条件)
      // await store.dispatch('user/getUserInfo')
      // 1. 判断后台是否返回了用户信息
      if (!store.getters.userId) {
        // 2. 获取后台返回的权限路由标识
        const menus = await store.dispatch('user/getUserInfo')
        // 3. 进行筛选权限路由
        const filterRoutes = asyncRoutes.filter(routes => menus.includes(routes.children[0].name))
        // ①将 404 添加到路由数组最后中. 解决刷新 404问题
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 4. 动态添加路由到内存中
        router.addRoutes(filterRoutes)
        // 5. 将有权限的路由添加到 Vuex 中,与静态路由合并
        store.commit('permission/setRoutes', filterRoutes)
        // ② 解决刷新又出现白屏
        // ③ 解决切换用户,若此用户没有上一个用户退出当前页面的权限,直接登陆显示 404 问题
        const allPaths = store.state.permission.routes.map(item => item.path)
        // ④ 解决员工详情页刷新时跳到首页的问题
        if (to.path === '/employees/detail') {
          next({ path: to.fullPath })
        } else {
          next({
            path: allPaths.includes(to.path) ? to.path : '/',
            replace: true
          })
        }
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }

  // 手动强制关闭进度条
  NProgress.done()
})

// 后置路由守卫
router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})

// import router from './router'
// import store from './store'
// import { Message } from 'element-ui'
// import NProgress from 'nprogress' // progress bar
// import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login'] // no redirect whitelist

// router.beforeEach(async(to, from, next) => {
//   // start progress bar
//   NProgress.start()

//   // set page title
//   document.title = getPageTitle(to.meta.title)

//   // determine whether the user has logged in
//   const hasToken = getToken()

//   if (hasToken) {
//     if (to.path === '/login') {
//       // if is logged in, redirect to the home page
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       const hasGetUserInfo = store.getters.name
//       if (hasGetUserInfo) {
//         next()
//       } else {
//         try {
//           // get user info
//           await store.dispatch('user/getInfo')

//           next()
//         } catch (error) {
//           // remove token and go to login page to re-login
//           await store.dispatch('user/resetToken')
//           Message.error(error || 'Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     /* has no token*/

//     if (whiteList.indexOf(to.path) !== -1) {
//       // in the free login whitelist, go directly
//       next()
//     } else {
//       // other pages that do not have permission to access are redirected to the login page.
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })

// router.afterEach(() => {
//   // finish progress bar
//   NProgress.done()
// })
